package com.csaba.connector.khb;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.csaba.connector.ServiceException;
import com.csaba.connector.khb.model.KHBBank;
import com.csaba.connector.khb.model.KHBSession;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractLoginService;
import com.csaba.connector.service.LogoutService;
import com.csaba.util.LoggerHelper;

/**
 * TODO implement ChangePasswordService in KHB
 * TODO implement DummyService in KHB
 * TODO implement permission checking in KHB
 * 
 * @author Gabe
 */
public class KHBLoginService extends AbstractLoginService implements Codes
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	@Override
	public void execute( final Session nullSession ) throws ServiceException
	{
		if ( customer == null )
			throw new ServiceException("Login service is not correctly initialized.");
		if ( nullSession != null )
			throw new ServiceException("Session is already initialized. Cannot login again in the same session.");

		logger.fine("KHB Login");
		session = new KHBSession();
		final KHBSession khb = (KHBSession) session;
		khb.setDebugFilePath("../khb.source/test/");

		//load login page for session ID
		final NameValuePair[] indexParams = new NameValuePair[] { //
		new BasicNameValuePair("fun", FUN_LOGIN_PREPIN),//
				new BasicNameValuePair("lang_id", "hu"),//
		};

		final String indexResult = khb.doPost(Codes.URL_RETAIL_ROOT, indexParams);
		khb.debugFile("index", indexResult);

		final NameValuePair[] loginParams = Util.extractForm(indexResult, "lite_pin_form",
				new NameValuePair[] { new BasicNameValuePair("fun", FUN_LOGIN_PRESMS) });
		Util.setPairValue(loginParams, "lite_pan", customer.getLoginId());
		Util.setPairValue(loginParams, "lite_pin", customer.getPassword());

		//post PIN and get SMS code
		final String loginResult = khb.doPost(Codes.URL_RETAIL_ROOT, loginParams);
		khb.debugFile("login", loginResult);

		//verify result
		if ( loginResult.contains("<title>Hiba") )//FIXME more sophisticated detection is required.
		{
			//login failed

			//FIXME extract error message

			throw new ServiceException("Login failed.");
		}

		try
		{
			//extract SMS OTP form and store in session - LiteSignForm
			final NameValuePair[] liteSignForm = Util.extractForm(loginResult, "LiteSignForm");
			session.setRemoteProperty(RP_LOGIN_OTPFORM, liteSignForm);

			//save customer details
			this.session.setCustomer(customer);
			customer.setId(customer.getLoginId());
			customer.setBank(KHBBank.getInstance());
			customer.setName("[KHB Customer - " + customer.getLoginId() + "]");
		}
		catch ( final Exception e1 )
		{
			final LogoutService service = new KHBLogoutService();
			try
			{
				service.execute(session);
			}
			catch ( final Exception e )
			{
				logger.log(Level.SEVERE, "Failed to logout after login.", e);
			}
			if ( e1 instanceof ServiceException )
				throw (ServiceException) e1;
			else
				throw new ServiceException("Fatal error during login.", e1);
		}
	}

}
